from common.request import JsonResponse, _Root
from dota.models import DotaFunctioneer, Video
import requests
from pyquery import PyQuery
import datetime
import re


class _Catch(_Root):

    def get(self):
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'}
        functioneers = self.db.query(DotaFunctioneer).all()
        self.db.close()
        for functioneer in functioneers:
            limit_param = self.db.execute('select publish_date, title from video where user_id=:user_id order by publish_date desc limit 1',
                                          {'user_id': functioneer.id}).first()
            self.db.commit()
            response = requests.get(functioneer.video_address, headers=headers)
            # print(response.text)
            jq = PyQuery(response.text)
            for child in jq('.videos-list .items>div').items():
                publish_date = self.switch_date(child.find('.v-publishtime').text())
                if not limit_param or not publish_date\
                   or (limit_param.publish_date == publish_date and limit_param.title != child.find('img').attr('alt'))\
                   or limit_param.publish_date < publish_date:
                    video = Video()
                    video.user_id = functioneer.id
                    video.title = child.find('img').attr('alt')
                    video.cover_address = child.find('img').attr('src')
                    video.duration = child.find('.v-time').text()
                    video.video_address = child.find('a').attr('href')
                    py = PyQuery(video.video_address)
                    str_script = py.find('body > script:last').text()
                    m = re.search(r'''playerUrl:'(?P<video_address>[^']+)',''', str_script)
                    m1 = re.search(r'''videoId:"(?P<video_id>[^"]+)"''', str_script)
                    m2 = re.search(r'''videoId2:"(?P<video_id_encryption>[^"]+)",''', str_script)
                    
                    if m:
                        video.video_flash_address = 'http:' + m.group('video_address')
                        video.src_video_id = m1.group('video_id')
                        video.src_video_id_encryption = m2.group('video_id_encryption')
                    video.publish_date = publish_date
                    self.db.add(video)
            self.db.commit()
        return JsonResponse(self, '50000', msg='获取成功！')

    def switch_date(self, str_date):
        if str_date:
            if str_date.find('天前') > -1:
                return datetime.date.today() + datetime.timedelta(days=-int(str_date[:-2]))
            elif len(str_date) == 11:
                return datetime.datetime.strptime(str(datetime.date.today().year) + '-' + str_date[:5], '%Y-%m-%d').date()
            elif len(str_date) == 10:
                return datetime.datetime.strptime(str_date, '%Y-%m-%d').date()
